import React from "react";
import api from "src/http/api";
import { StorageProps, IdcInfosProps } from "src/utils/interface";

import {
  Drawer,
  Descriptions,
  Tag,
  Spin,
  Typography,
  Table,
  TableProps,
} from "antd";

const { useEffect, useState, memo } = React;

interface Props {
  storageUri: string;
  visible: boolean;
  onClose: () => void;
}

const StorageInfoDrawer: React.FC<Props> = (props) => {
  const [data, setData] = useState({} as StorageProps);

  const spinning =
    props.storageUri && data?.storageUri !== props.storageUri ? true : false;

  const descriptions = [
    {
      label: "Uri",
      key: "storageUri",
      value: data.storageUri,
    },
    {
      label: "Type",
      key: "type",
      value: <Tag color="blue">{data.type}</Tag>,
    },
    {
      label: "Owners",
      key: "owners",
      value: (
        <div style={{ color: "#1890ff", cursor: "pointer" }}>
          {data.owners?.join(" ")}
        </div>
      ),
    },
    {
      label: "Description",
      key: "description",
      value: data.description,
    },
  ];

  const tableProps: TableProps<IdcInfosProps> = {
    bordered: true,
    rowKey: "idc",
    loading: data.idcInfos?.length === 0,
    dataSource: data.idcInfos,
    pagination: { hideOnSinglePage: true },
    columns: [
      {
        title: "Idc",
        dataIndex: "idc",
        render: (value: string[]) =>
          value?.map((item) => (
            <Tag color="blue" key={item}>
              {item}
            </Tag>
          )),
      },
      {
        title: "Psm",
        dataIndex: "psm",
      },
      {
        title: "Owners",
        dataIndex: "owners",
        render: (value: string[]) => (
          <div style={{ color: "#1890ff", cursor: "pointer" }}>
            {data.owners?.join(" ")}
          </div>
        ),
      },
    ],
  };

  useEffect(() => {
    api.getStorageByStorageUri(props.storageUri).then((res: any) => {
      setData(res.data);
    });
  }, [props.storageUri]);

  return (
    <Drawer
      title="Storage Info"
      placement="right"
      width={700}
      onClose={props.onClose}
      visible={props.visible}
    >
      <Spin spinning={spinning} tip="loading...">
        <Descriptions title="Basic Info" column={1}>
          {descriptions.map((item) => (
            <Descriptions.Item label={item.label} key={item.key}>
              {item.value}
            </Descriptions.Item>
          ))}
        </Descriptions>
        <Typography.Title level={5} style={{ fontWeight: 700 }}>
          IdcInfo
        </Typography.Title>
        <Table {...tableProps} />
      </Spin>
    </Drawer>
  );
};

export default memo(StorageInfoDrawer);
